//
//  XQTabBarController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/18.
//

#import "XQTabBarController.h"
#import <Masonry/View+MASAdditions.h>

@interface XQTabBarController ()

@property (nonatomic, assign) NSInteger preSelectedIndex;

@end

@implementation XQTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tabBar setHidden:YES];
    [self.view addSubview:self.t_tabBar];
    [self.t_tabBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.bottom.offset(0);
        make.height.equalTo(@([[UIScreen mainScreen] tabBarHeight] + [[UIScreen mainScreen] bottomHeight]));
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    if (self.selectedIndex == selectedIndex) return;
    self.preSelectedIndex = self.selectedIndex;
    
    [super setSelectedIndex:selectedIndex];
    
    if (selectedIndex < self.viewControllers.count) {
        self.t_tabBar.selectedIndex = selectedIndex;
    }
}

- (BOOL)willTabControllerAtIndex:(NSInteger)index {
    return YES;
}

- (void)goBack {
    self.selectedIndex = self.preSelectedIndex;
}

- (void)callRefreshHandleAtViewController:(UIViewController<XQTabBarProtocol> *)vc {
    if ([vc respondsToSelector:@selector(ti_tabBarDoubleTapHandle)]) {
        [vc ti_tabBarDoubleTapHandle];
    }
    for (UIViewController<XQTabBarProtocol> *child in vc.childViewControllers) {
        [self callRefreshHandleAtViewController:child];
    }
}

- (XQTabBar *)t_tabBar {
    if (!_t_tabBar) {
        _t_tabBar = [[XQTabBar alloc] init];
        _t_tabBar.backgroundColor = [UIColor whiteColor];
        @weakify(self);
        _t_tabBar.selectedTabBarItem = ^(NSInteger idx) {
            @strongify(self);
            if ([self willTabControllerAtIndex:idx]) {
                self.selectedIndex = idx;
            }
        };
        _t_tabBar.doubleTapTabBarItem = ^(NSInteger idx) {
            @strongify(self);
            if (idx < self.viewControllers.count) {
                [self callRefreshHandleAtViewController:self.viewControllers[idx]];
            }
        };
    }
    return _t_tabBar;
}


@end
